
import { getAction } from '@/api/manage'
import { getSubBandProtect, getWaveBeamList, getSubBandList, sendSubBandExchangeRelation } from '@/api/load'
import { transformSubBandList } from '@/utils/load'

const configuration = {
  state: {
    // 最小用户宽带占用 0.5 MHz 
    minRequestBandWidth: 0.5, 
    // 保护间隔
    protectValue: '',

    // 波束数据
    upWaveBeamList: [],
    downWaveBeamList: [],

    // 当前选择的上下行波束id
    upWaveBeamTargetId: '',
    downWaveBeamTargetId: '',

    // 原始子带数据
    initUpSubBandList: [],
    initDownSubBandList: [],

    // 处理后的子带数据
    upSubBandList: [],
    downSubBandList: [],
    
    // 上下行子带数据存储
    subBandList: [],

    // 删除的子带mergeId集合
    removeMergeIds: [],
    // 发送 配置好的子带用户信息集合
    subBandExchangeRelationSaveDTOList: [],
    // 在进入配置页面的时候，记录时间戳
    timestamp: 0
  },

  mutations: {
    ADD_SUBBANDEXCHANGERELATION: (state, params) => {
      params.bandList.forEach(item => {
        let upSubBand = state.upSubBandList.find(subBandItem => subBandItem.id === item.upSubBandId)
        upSubBand.exchangeRelationList.push({
          ...item,
          upUserName: params.upUserName,
          upWaveBeamId: params.upWaveBeamId,
          downUserName: params.downUserName,
          downWaveBeamId: params.downWaveBeamId,
          mergeId: params.mergeId
        })
        // delete upSubBand.render
        if (upSubBand.mergeId) {
          upSubBand.mergeId.push(params.mergeId)
        } else {
          upSubBand.mergeId = [params.mergeId]
        }
        const tempUpSubBand = JSON.parse(JSON.stringify(upSubBand))
        delete tempUpSubBand.render
        upSubBand.render = transformSubBandList([tempUpSubBand], state.protectValue, 'up', params.isCopy)[0].render

        let downSubBand = state.downSubBandList.find(subBandItem => subBandItem.id === item.downSubBandId)
        
        downSubBand.exchangeRelationList.push({
          ...item,
          upUserName: params.upUserName,
          upWaveBeamId: params.upWaveBeamId,
          downUserName: params.downUserName,
          downWaveBeamId: params.downWaveBeamId,
          mergeId: params.mergeId
        })
        // delete downSubBand.render
        if (downSubBand.mergeId) {
          downSubBand.mergeId.push(params.mergeId.toString())
        } else {
          downSubBand.mergeId = [params.mergeId.toString()]
        }
        const tempDownSubBand = JSON.parse(JSON.stringify(downSubBand))
        delete tempDownSubBand.render
        downSubBand.render = transformSubBandList([tempDownSubBand], state.protectValue, 'down')[0].render
      })
    },
    SET_TIMESTAMP: (state) => {
      state.timestamp = new Date().getTime()
    },
    SET_REMOVEMERGEIDS: (state, params) => {
      if (params.type === 'init') {
        state.removeMergeIds = []
        return
      }
      state.removeMergeIds.push(params.mergeId)
    },
    SET_SUBBANDEXCHANGERELATIONSAVEDTOLIST: (state, params) => {
      console.log('params', params);
      if (params.type === 'init') {
        state.subBandExchangeRelationSaveDTOList = []
        return
      }
      if (params.type === 'add') {
        state.subBandExchangeRelationSaveDTOList.push(params.relation)
      } else {
        // 对vuex中，存储的发送数据进行删除
        state.subBandExchangeRelationSaveDTOList = state.subBandExchangeRelationSaveDTOList.filter(item => item.mergeId != params.relation.mergeId)
        
        // 对当前下行 波束中的 交链关系进行 删除
        const downSubBand = state.downSubBandList.filter(item => item.mergeId && item.mergeId.indexOf(params.relation.mergeId.toString()) != -1)
        transformBubItem(downSubBand)

        // 对subBandList所有波束中的 上行波束的 交链关系进行 删除
        const result = state.subBandList.find(item => item.id == params.relation.upWaveBeamId)
        const upSubBand = result.list.filter(item => item.mergeId && item.mergeId.indexOf(params.relation.mergeId) != -1)
        if (upSubBand) transformBubItem(upSubBand)
        
        function transformBubItem(subList) {
          subList.forEach(subItem => {
            if (subItem.exchangeRelationList.length === 1) {
              if (subItem.copyNum && subItem.copyNum > 1 ) {
                subItem.copyNum -= 1
              } else {
                subItem.render = [
                  { type: 'guard', width: state.protectValue / subItem.bandWidth * 100 },
                  { type: 'empty' },
                  { type: 'guard', width: state.protectValue / subItem.bandWidth * 100 }
                ]
              }
            } else {
              if (subItem.copyNum && subItem.copyNum > 1 ) {
                subItem.copyNum -= 1
              } else {
                let firstFlag = false
                let lastFlag = false
                subItem.render = subItem.render.filter((renderItem, index) => {
                  if (renderItem.mergeId && renderItem.mergeId == params.relation.mergeId) {
                    if (index === 0) {
                      firstFlag = true
                    } else if (index === subItem.render.length - 1) {
                      lastFlag = true
                    }
                  }
                  return !(renderItem.mergeId && renderItem.mergeId == params.relation.mergeId)
                })
                if (firstFlag) {
                  if (subItem.render[0].type === 'guard') {
                    subItem.render.shift()
                  }
                  subItem.render.unshift({ type: 'guard', width: state.protectValue / subItem.bandWidth * 100 })
                }
                if (lastFlag) {
                  subItem.render.push({ type: 'guard', width: state.protectValue / subItem.bandWidth * 100 })
                }
                console.log('多个', subItem.render);
              }
            }
            subItem.exchangeRelationList = subItem.exchangeRelationList.filter(item => item.mergeId !== params.relation.mergeId)
          })
        }
      }
    },
    // 保护间隔 赋值
    SET_PROTECTVALUE: (state, protectValue) => {
      state.protectValue = protectValue
    },
    // 波束数据 赋值
    SET_UPWAVEBEANLIST: (state, upWaveBeamList) => {
      state.upWaveBeamList = upWaveBeamList
    },
    SET_DOWNWAVEBEAMLIST: (state, downWaveBeamList) => {
      state.downWaveBeamList = downWaveBeamList
    },
    // 当前选择的上下行波束id 赋值
    SET_UPWAVEBEANTARGETID: (state, upWaveBeamTargetId) => {
      state.upWaveBeamTargetId = upWaveBeamTargetId
    },
    SET_DOWNWAVEBEANTARGETID: (state, downWaveBeamTargetId) => {
      state.downWaveBeamTargetId = downWaveBeamTargetId
    },
    // 子带数据 赋值
    SET_UPSUBBANDLIST: (state, waveBeam) => {
      console.log('waveBeam', waveBeam);
      const temp = JSON.parse(JSON.stringify(waveBeam.list))
      state.initUpSubBandList = temp
      state.upSubBandList = transformSubBandList(temp, state.protectValue, 'up')
      state.upSubBandList = state.upSubBandList.map(item => {
        if (item.exchangeRelationList && item.exchangeRelationList.length) {
          const mergeIds = item.exchangeRelationList.map(mergeItem => mergeItem.mergeId)
          if(item.copyMergeId) mergeIds.push(...item.copyMergeId)
          return {...item, mergeId: mergeIds}
        } else {
          return item
        }
      })
      state.subBandList.push({id: waveBeam.id, list: state.upSubBandList})
    },
    SET_DOWNSUBBANDLIST: (state, waveBeam) => {
      const temp = JSON.parse(JSON.stringify(waveBeam.list))
      state.initDownSubBandList = temp
      state.downSubBandList = transformSubBandList(temp, state.protectValue, 'down')
      state.downSubBandList = state.downSubBandList.map(item => {
        if (item.exchangeRelationList && item.exchangeRelationList.length) {
          const mergeIds = item.exchangeRelationList.map(mergeItem => mergeItem.mergeId)
          return {...item, mergeId: mergeIds}
        } else {
          return item
        }
      })
      state.subBandList.push({id: waveBeam.id, list: state.downSubBandList})
    },
    // 清空暂存数据中的子带列表 state.subBandList = []
    CLEAR_SUBBANDLIST: (state) => {
      state.subBandList = []
    },
    // （下拉框）切换子带后，对子带数据赋值
    SET_SUBBANDLIST(state, subBand) {
      state[subBand.type === 'up' ? 'upSubBandList' : 'downSubBandList'] = subBand.list
    },
    // 设置子带、用户、用户关联子带的变量，为true时，对应的div亮
    SET_SUBBANDRELATIONFLAG: (state, obj) => {
      let copyMergeId = []
      state.upSubBandList.forEach(item => {
        if (item.mergeId && item.mergeId.indexOf(obj.mergeId) !== -1) {
          if (obj.prop === 'subNameFlag') {
            item[obj.prop] = obj.flag
          } else {
            if (item.copyMergeId && item.copyMergeId.length) {
              copyMergeId = item.copyMergeId
            }
            item.render.forEach(renderItem => {
              if(renderItem.id && renderItem.mergeId === obj.mergeId) renderItem[obj.prop] = obj.flag
            })
          }
        }
      })
      state.downSubBandList.forEach(item => {
        if (item.mergeId && item.mergeId.indexOf(obj.mergeId) !== -1) {
          if (obj.prop === 'subNameFlag') {
            item[obj.prop] = obj.flag
          } else {
            item.render.forEach(renderItem => {
              if(renderItem.id && renderItem.mergeId === obj.mergeId) renderItem[obj.prop] = obj.flag
            })
          }
        }
      })
      if (copyMergeId) {
        copyMergeId.forEach(copyItem => {
          state.downSubBandList.forEach(item => {
            if (item.mergeId && item.mergeId.indexOf(copyItem) !== -1) {
              item.render.forEach(renderItem => {
                if(renderItem.id && renderItem.mergeId === copyItem) renderItem[obj.prop] = obj.flag
              })
            }
          })
        })
      }
    }
  },
  actions: {
    // 获取波束列表
    GetSubBandProtect({ commit }) {
      const that = this
      return new Promise((resolve, reject) => {
        getSubBandProtect().then(response => {
          if (response.success) {
            commit('SET_PROTECTVALUE', response.result.protectValue)
            resolve(response)
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取波束列表
    GetWaveBeamList({ commit, state }, params) {
      const that = this
      return new Promise((resolve, reject) => {
        getWaveBeamList(params).then(response => {
          if (response.success) {
            commit(params.upDownDirection === 'up' ? 'SET_UPWAVEBEANLIST' : 'SET_DOWNWAVEBEAMLIST', response.result.records)
            if (!state[params.upDownDirection === 'up' ? 'upWaveBeamTargetId' : 'downWaveBeamTargetId']) {
              commit(params.upDownDirection === 'up' ? 'SET_UPWAVEBEANTARGETID' : 'SET_DOWNWAVEBEANTARGETID', response.result.records[0].id)
            }
            resolve(response)
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取子带列表
    GetSubBandList({ commit, state }, params) {
      return new Promise((resolve, reject) => {
        getSubBandList({ pageSize: -1, waveBeamId: params.waveBeamId || (params.type === 'up' ? state.upWaveBeamTargetId : state.downWaveBeamTargetId) }).then(response => {
          if (response.success) {
            commit(params.type === 'up' ? 'SET_UPSUBBANDLIST' : 'SET_DOWNSUBBANDLIST', { list: response.result.records, id: params.waveBeamId || (params.type === 'up' ? state.upWaveBeamTargetId : state.downWaveBeamTargetId) })
            if (params.waveBeamId) {
              commit(params.type === 'up' ? 'SET_UPWAVEBEANTARGETID' : 'SET_DOWNWAVEBEANTARGETID', params.waveBeamId)
            }
            resolve(response)
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取所有子带列表
    GetAllSubBandByTypeList({ commit, state }, upDownDirection) {
      return new Promise((resolve, reject) => {
        getSubBandList({ pageSize: -1, upDownDirection: upDownDirection }).then(response => {
          if (response.success) {
            // commit(params.type === 'up' ? 'SET_UPSUBBANDLIST' : 'SET_DOWNSUBBANDLIST', { list: response.result.records, id: params.waveBeamId || (params.type === 'up' ? state.upWaveBeamTargetId : state.downWaveBeamTargetId) })
            // if (params.waveBeamId) {
            //   commit(params.type === 'up' ? 'SET_UPWAVEBEANTARGETID' : 'SET_DOWNWAVEBEANTARGETID', params.waveBeamId)
            // }
            resolve(response)
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    SendSubBandExchangeRelation({ commit, state }) {
      const params = {
        removeMergeIds: state.removeMergeIds,
        subBandExchangeRelationSaveDTOList: state.subBandExchangeRelationSaveDTOList
      }
      return new Promise((resolve, reject) => {
        sendSubBandExchangeRelation(params).then(response => {
          if (response.success) {
          commit('CLEAR_SUBBANDLIST')
          commit('SET_REMOVEMERGEIDS', { type: 'init' })
          commit('SET_SUBBANDEXCHANGERELATIONSAVEDTOLIST', { type: 'init' })
          resolve(response)
        }else{
          reject(response)
        }
        }).catch(error => {
          reject(error)
        })
      })
    }
  },
  getters: {
    // 上行子带数据轴
    upDatumAxis(state) {
      let arr = [], start = [], end = []
      arr = state.upSubBandList.map((item,index) => {
        if (index === 0) start = [Number.MIN_VALUE, item.startFrenquency]
        if (index === state.upSubBandList.length - 1) end = [item.endFrequency, Number.MAX_VALUE]
        if (item.exchangeRelationList && item.exchangeRelationList.length) {
          return [item.startFrenquency, item.endFrequency]
          // if (item.exchangeRelationList.length === 1) {
          //   // const guardSpace = item.exchangeRelationList[0].BandRequestBandWidth > 
          //   if (item.exchangeRelationList[0].BandProtectStartFrenquency) {
              
          //   }
          // } else {
          //   return [item.startFrenquency, item.endFrequency]
          // }
        }

      }).filter(i => typeof i !== 'undefined')
      arr.unshift(start)
      arr.push(end)

      return arr
    },
    // 下行子带数据轴
    downDatumAxis(state) {
      let arr = [], start = [], end = []
      arr = state.downSubBandList.map((item,index) => {
        if (index === 0) start = [Number.MIN_VALUE, item.startFrenquency]
        if (index === state.downSubBandList.length - 1) end = [item.endFrequency, Number.MAX_VALUE]
        if (item.exchangeRelationList && item.exchangeRelationList.length) {
          return [item.startFrenquency, item.endFrequency]
          // if (item.exchangeRelationList.length === 1) {
          //   // const guardSpace = item.exchangeRelationList[0].BandRequestBandWidth > 
          //   if (item.exchangeRelationList[0].BandProtectStartFrenquency) {
              
          //   }
          // } else {
          //   return [item.startFrenquency, item.endFrequency]
          // }
        }

      }).filter(i => typeof i !== 'undefined')
      arr.unshift(start)
      arr.push(end)

      return arr
    },
  }
}

export default configuration